package com.qk.manangement.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.properties.CacheProperties;
import com.qk.common.properties.RedisExpTimeProperties;
import com.qk.common.properties.RedisProperties;
import com.qk.common.properties.UserPasswordProperties;
import com.qk.common.response.*;
import com.qk.common.utils.AliOssUtil;
import com.qk.common.utils.JwtUtils;
import com.qk.entity.pojo.OperateLog;
import com.qk.entity.pojo.User;
import com.qk.entity.request.user.LoginRequest;
import com.qk.manangement.mapper.BusinessMapper;
import com.qk.manangement.mapper.ClueMapper;
import com.qk.manangement.mapper.OperateLogMapper;
import com.qk.manangement.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@Slf4j
public class OtherController {
   // execution(public * com..*Service.*(..))
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPasswordProperties userPasswordProperties;
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private StringRedisTemplate redisClient;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private Cache<String, OverviewVO> cache;
    @Autowired
    private RedisExpTimeProperties redisConfigProperties;
    @Autowired
    private JwtUtils jwtUtils;



    @PostMapping("/upload")
    public Result upload(@RequestParam("image") MultipartFile file) throws Exception {
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        String upload = aliOssUtil.upload(file.getBytes(), "avatar/" + fileName);
        return Result.success(upload);
    }

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        //参数校验
        if (loginRequest == null) {
            return Result.error("参数错误");
        }
        if (StrUtil.isBlank(loginRequest.getUsername()) || StrUtil.isBlank(loginRequest.getPassword())) {
            return Result.error("用户名密码不能为空");
        }

        User dbUser = userMapper.getByUsername(loginRequest.getUsername());
        if (dbUser == null) {
            return Result.error("用户名密码错误");
        }

        //md5加密比对
        String encryptedPassword = SecureUtil.md5(loginRequest.getPassword() + userPasswordProperties.getSalt());
        if (ObjectUtil.equals(encryptedPassword, dbUser.getPassword())) {
            //生成jwt令牌
            Map<String, Object> jwtMap = new HashMap<>();
            jwtMap.put("id", dbUser.getId());
            jwtMap.put("username", dbUser.getUsername());
            jwtMap.put("name", dbUser.getName());

            // 使用配置化的过期时间和密钥生成token
            String token = jwtUtils.generateToken(jwtMap);

            LoginResponse loginResponseById = userMapper.getLoginResponseById(dbUser.getId());
            if (loginResponseById != null) {
                loginResponseById.setToken(token);
                return Result.success(loginResponseById);
            }
            return Result.error("用户不存在");
        }
        return Result.error("用户名密码错误");
    }


    @GetMapping("/report/overview")
    public Result overview() {
        String key = RedisProperties.REDIS_KEY_PREFIX + RedisProperties.REDIS_KEY_OVERVIEW;

        // 一级缓存：Caffeine
        OverviewVO cached = cache.getIfPresent(CacheProperties.CACHE_KEY);
        if (cached != null) {
            return Result.success(cached);
        }

        try {
            // 二级缓存：Redis
            String redisValue = redisClient.opsForValue().get(key);
            if (redisValue != null) {
                OverviewVO redisCached = JSONUtil.toBean(redisValue, OverviewVO.class);
                cache.put(CacheProperties.CACHE_KEY, redisCached); // 回写本地缓存
                return Result.success(redisCached);
            }
        } catch (Exception e) {
            log.error("Redis缓存读取异常: {}", e.getMessage());
        }

        // 三级存储：数据库
        OverviewBussinessVO businessVO = businessMapper.getOvewInfor();
        OverviewClueVO clueVO = clueMapper.getOverviewInfor();

        OverviewVO overviewVO = BeanUtil.copyProperties(businessVO, OverviewVO.class);
        BeanUtil.copyProperties(clueVO, overviewVO);

        // 回写缓存
        try {
            String jsonStr = JSONUtil.toJsonStr(overviewVO);
            redisClient.opsForValue().set(key, jsonStr, Duration.ofSeconds(redisConfigProperties.getOverviewExpireTime()));
            cache.put(CacheProperties.CACHE_KEY, overviewVO); // 回写本地缓存
        } catch (Exception e) {
            log.error("缓存写入异常: {}", e.getMessage());
        }

        return Result.success(overviewVO);
    }


    /**
     * 获取日志列表
     */
    @GetMapping("/logs")
    public Result logs(String operateUserName,@RequestParam(defaultValue = "1") Integer page, @RequestParam (defaultValue = "10") Integer pageSize) {
        if (page == null || pageSize == null) {
            return Result.error("参数错误");
        }
        PageHelper.startPage(page, pageSize);
        List<LogListResponse> logListResponses = operateLogMapper.pageList(operateUserName);
        PageInfo<LogListResponse> logListResponsePageInfo = new PageInfo<>(logListResponses);
        return Result.success(new PageResult<LogListResponse>( logListResponsePageInfo.getTotal(), logListResponses));
    }


}
